<template>
  <div>
    <!-- <button @click="checkAll">click</button> -->
    <el-tree
      ref="treeRef"
      :data="treeList"
      :props="treeProps"
      show-checkbox
      node-key="id"
      :default-expanded-keys="treeList.openList"
      :default-checked-keys="treeList.checkeds"
      @check="checkAll"
    ></el-tree>
  </div>
  <div class="btn">
    <el-button type="primary" @click="saveLisr">保存</el-button>
    <el-button @click="clearCheckeds">清空</el-button>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, ElTree } from "element-plus";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { treeListApi, getUserMenuByIdApi, allocMenuApi } from "./api";

type ITreelist = ItreeMenu[] & {
  checkeds?: number[];
  openList?: number[];
};

const route = useRoute();
const router = useRouter();

const treeProps = {
  // children属性是要告诉 tree 组件，在data里面哪个属性名是用来作用子级的
  children: "children",
  //   lable 是告诉 tree组件，在data里面哪个属性是用来显示文字的
  label: "title",
};

// 选框改变事件
const treeRef = ref<InstanceType<typeof ElTree>>();
const checkAll = () => {
  treeList.value.checkeds = treeRef.value!.getCheckedKeys(true) as number[];
  //   console.log(123, treeRef.value!.getCheckedKeys(true));
  //   console.log(treeList.value.checkeds);
};

// 提交分配菜单
const saveLisr = () => {
  ElMessageBox.confirm("是否为该角色分配菜单？", "分配菜单", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allocMenuApi({
        roleId: parseInt(route.query.id as string),
        menuIds: treeList.value.checkeds!,
      });
      router.push("/ums/role");
      ElMessage.success("提交成功");
    })
    .catch(() => {});
};

// 清空选中
const clearCheckeds = () => {
  treeRef.value!.setCheckedKeys([], false);
  treeList.value.checkeds = [];
  // console.log(treeList.value.checkeds);
};

const treeList = ref<ITreelist>([]);
Promise.all([
  treeListApi(),
  getUserMenuByIdApi(parseInt(route.query.id! as string)),
]).then((res) => {
  // console.log(res);
  treeList.value = res[0].data;
  // 添加到选中的id数组
  treeList.value.checkeds = res[1].data
    .filter((item) => item.parentId !== 0)
    .map((item) => item.id);

  // 默认展开的数组
  treeList.value.openList = Array.from(
    new Set(res[0].data.map((item) => item.id))
  );
  // console.log(treeList.value.openList);
});
</script>

<style scoped>
.btn {
  padding: 20px 0;
  display: flex;
  justify-content: center;
}
</style>
